<template>
  <div :ref="'container'" class="mood" tabindex="0" @keydown="onKeyDown"
    :style="{ height: props.params.eGridCell.offsetHeight + 'px', width: props.params.eGridCell.offsetWidth + 'px', display: 'flex', gap: '8px', 'alignItems': 'center' }">
    <select ref="selectRef" class="editorSel" v-model="selVal" style="width: 100%; height: 100%;" @blur="onBlur">
      <option v-for="item in props.params.values" :key="item.value" :label="item.label" :value="item.value"
        @click="onClick(item.value)" />
    </select>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';

interface MoodEditorParams {
  value: string;
  values: Array<{ label: string; value: string }>;
  stopEditing: () => void;
  eGridCell: HTMLDivElement
}

// table 传递进来的值
const props = defineProps<{
  params: MoodEditorParams;
}>();

// 本地的值, 只在本地进行操作, 通过 getValue 将本地值进行返回
const selVal = ref("props.params.value");

// watchEffect(() => {
//   // 获取params中的数据
//   console.log(props.params);
//   console.log(props.params.eGridCell.offsetWidth)
//   console.log(props.params.eGridCell.offsetHeight)
// });

const setValue = (value: string) => {
  selVal.value = value;
};

const onBlur = () => {
  // props.params.stopEditing();
}

const onClick = (value: string) => {
  setValue(value);
  nextTick(() => props.params.stopEditing())
};

const container = ref<HTMLElement>();
const setInitialValue = () => {
  setValue(props.params.value);
};

const selectRef = ref<HTMLSelectElement>();
// 设置默认值
onMounted(() => {
  setInitialValue();
  nextTick(() => {
    selectRef.value!.style.border = '1px solid #d9d9db';

    if (container.value) {
      container.value.focus();
    }
  });
});

// 返回 value 的值
const getValue = () => {
  return selVal.value;
};

//
const isPopup = () => {
  return true;
};

const onKeyDown = (event: KeyboardEvent) => {
  const key = event.key;
  if (
    key === 'ArrowLeft' || // left
    key === 'ArrowRight' // right
  ) {
    event.stopPropagation();
  }
};

// 导出 value
defineExpose({
  getValue,
  isPopup
})
</script>

<style scoped>
/* 在 table cellEditor 组件中 scoped 无效 */
</style>
